package com.xaaef.grpc.server.rpc;


import com.xaaef.grpc.lib.consts.GlobalConst;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.error.GrpcExceptionInterceptor;
import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class GrpcGlobalExceptionHandler {


    @Bean
    @GrpcGlobalServerInterceptor
    public GrpcExceptionInterceptor grpcExceptionInterceptor() {
        return new GrpcExceptionInterceptor((serverCall, error) -> {
            serverCall.close(Status.INTERNAL
                    .withCause(error)
                    .withDescription(error.getMessage()), new Metadata());
        });
    }


    @Bean
    @GrpcGlobalServerInterceptor
    public ServerInterceptor globalTokenServerInterceptor() {
        return new ServerInterceptor() {
            @Override
            public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> serverCall,
                                                                         Metadata metadata,
                                                                         ServerCallHandler<ReqT, RespT> serverCallHandler) {
                var tenantId = metadata.get(GlobalConst.TENANT_ID);
                log.info("address : {}  TenantId: {} ", serverCall.getMethodDescriptor().getFullMethodName(), tenantId);
                return serverCallHandler.startCall(serverCall, metadata);
            }
        };
    }


}

